﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ImageEffect
{
    /// <summary>
    /// Class for doing a box blur
    /// </summary>
    class BoxBlur
    {
        #region Static Functions
        /// <summary>
        /// Does a box blur on the array passed in
        /// </summary>
        /// <param name="Values">Array of values to blur</param>
        /// <param name="Width">Width of the array</param>
        /// <param name="Height">Height of the array</param>
        /// <param name="HRadius">Width of the box</param>
        /// <param name="VRadius">Height of the box</param>
        /// <returns>returns a blurred version of the input array</returns>
        public static float[,] Blur(float[,] Values, int Width, int Height)
        {
            int BoxWidth = 2;
            int BoxHeight = 2;

            float[,] FinalValues = new float[Width, Height];
            for (int y = 0; y < Height; ++y)
            {
                for (int x = (BoxWidth / 2); x < Width; ++x)
                {
                    float Sum = 0.0f;
                    for (int x2 = -(BoxWidth / 2); x2 < (BoxWidth / 2); ++x2)
                    {
                        for (int y2 = -(BoxHeight / 2); y2 < (BoxHeight / 2); ++y2)
                        {
                            int xIdx = Math.Min(Math.Max(x + x2, 0), Width - 1);
                            int yIdx = Math.Min(Math.Max(y + y2, 0), Height - 1);
                            Sum += Values[xIdx, yIdx];
                        }
                    }
                    FinalValues[(x + BoxWidth / 2) % Width, y] = Sum / (float)(BoxWidth + BoxHeight);
                }

                // Remove the distortion that shows up on the left side of the image
                for (int x = 0; x < BoxWidth; x++)
                    FinalValues[x, y] = FinalValues[x + BoxWidth, y];
            }
            return FinalValues;
        }
        #endregion
    }
}

